﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Xml.Linq;
using System.Linq;
using System.Reflection;
using System.IO;
using MicropleSoft.WmsApp.Library.ApplicationCache;
using MicropleSoft.WmsApp.Library.ServiceFacade;

namespace MicropleSoft.WmsApp.Library.Common
{
    public class LocalBaseDataWrapBuilder : ILocalBaseDataWrapBuilder
    {
        /// <summary>
        ///  根据xml文件，构造Wrap对象，放入缓存
        ///  构建方法，先构建表结构，然后放入数据，然后赋予LocalBaseDataWrap对象
        /// </summary>
        /// <param name="xmlName"></param>
        /// <param name="stream"></param>
        public void BuildBaseDataWrap(string xmlName,Stream stream)
        {
            
            var root = XElement.Load(stream);

            //找到schema节点
            var schemas = from element in root.Descendants("Schema")
                           select element;

            if(schemas.First() == null)
            {
                throw new Exception("不存在schema节点" + xmlName);
            }

            var localBaseDataWrap = new LocalBaseDataWrap(xmlName);
            localBaseDataWrap.PBaseDataWrapType = BaseDataWrapType.Client;
            //构建一张表
            localBaseDataWrap.BaseDataSource = new DataTable(xmlName);

            localBaseDataWrap.DataKey = xmlName;

            localBaseDataWrap.LookUpViewHeaderList = new List<LookUpViewHeader>();
            var elts = from xe in schemas.First().Elements()
                           select xe;
            //1 循环加入列
            //2 将LookUpViewHeader的List填满
            foreach (XElement xElement in elts)
            {
                var dataColumn = new DataColumn
                                     {
                                         DataType = Type.GetType(xElement.Attribute("Type").Value),
                                         ColumnName = xElement.Attribute("Field").Value,
                                         Caption = xElement.Attribute("Caption").Value
                                     };

                localBaseDataWrap.BaseDataSource.Columns.Add(dataColumn);

                var header = new LookUpViewHeader();
                if (xElement.Attribute("Field") != null)
                {
                    header.Field = xElement.Attribute("Field").Value;
                }
                else
                {
                    throw new Exception("的属性Field不能为空！");
                }

                header.Caption = (String) xElement.Attribute("Caption").Value;
                header.Width = Int32.Parse(xElement.Attribute("Width").Value);

                header.IsEditValue = false;
                header.IsDisplayValue = false;
                if (schemas.First().Attribute("ValueMember").Value == xElement.Attribute("Field").Value)
                {
                    header.IsEditValue = true;
                }

                if (schemas.First().Attribute("DisplayMember").Value == xElement.Attribute("Field").Value)
                {
                    header.IsDisplayValue = true;
                }

                if (xElement.Attribute("IsVisual") != null)
                {
                    header.IsVisual = Boolean.Parse(xElement.Attribute("IsVisual").Value);
                }
                else
                {
                    header.IsVisual = true;
                }

                localBaseDataWrap.LookUpViewHeaderList.Add(header);
            }

            //往表中填入数据
            //找到Data节点
            var datas = from element in root.Descendants("Data")
                           select element;

            foreach (XElement xElement in datas.Elements())
            {
                DataRow dr = localBaseDataWrap.BaseDataSource.NewRow();
                foreach (XElement xe in elts)
                {
                    try
                    {
                        dr[xe.Attribute("Field").Value] = xElement.Attribute(xe.Attribute("Field").Value).Value;
                    }
                    catch (Exception exception)
                    {
                        throw new Exception("加载资源文件数据时出错：" + xmlName + "\n\r" + exception.Message);
                    }
                    
                }
                localBaseDataWrap.BaseDataSource.Rows.Add(dr);
            }
            localBaseDataWrap.BaseDataSource.AcceptChanges();
        
            CacheManage.GetDataCache().AddData(xmlName,localBaseDataWrap);
        }
    }
}
